package dao;

import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ChatClientDao {
    Util util = new Util();
    Connection con = null;

    public List<String> selectUsers1(String username) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<String> users = new ArrayList<>();

        try {
            con = util.getConnection();

            String sql = "SELECT username1 FROM friendships WHERE username2 = ? AND status = 0";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, username);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                String user = resultSet.getString("username1");
                users.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException("Error querying database", e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (preparedStatement != null) preparedStatement.close();
                if (con != null) con.close();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
        return users;
    }

    public List<String> selectUsers2(String username) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<String> users = new ArrayList<>();

        try {
            con = util.getConnection();

            String sql = "SELECT username2 FROM friendships WHERE username1 = ? AND status = 0";
            preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, username);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                String user = resultSet.getString("username2");
                users.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException("Error querying database", e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (preparedStatement != null) preparedStatement.close();
                if (con != null) con.close();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
        return users;
    }
}